package cn.walls1717.juc.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 死锁测试<br>
 *
 * 死锁的检查：<br>
 * 1.jsp -l 获取到出问题的程序id jstack id 查看状态<br>
 * 2.jconsole或jvisualvm可视化界面检测死锁<br>
 *
 * @author walls1717
 * @create 2022/12/10 11:07
 **/
@Slf4j
public class DeadLockDemo {

    public static void main(String[] args) {
        final Object A = new Object();
        final Object B = new Object();

        new Thread(() -> {
            synchronized (A) {
                log.info("获得A锁，希望获得B锁");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (B) {
                    log.info("获得B锁");
                }
            }
        }, "t1").start();

        new Thread(() -> {
            synchronized (B) {
                log.info("获得B锁，希望获得A锁");
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (A) {
                    log.info("获得A锁");
                }
            }
        }, "t2").start();
    }
}
